package org.thanos.demo.nats.config;

import org.thanos.demo.nats.AsyncNatsConsumerPool;
import org.thanos.demo.nats.NatsClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.util.StringUtils;

import java.io.IOException;

@Configuration
@SpringBootConfiguration
@EnableConfigurationProperties(NatsProperties.class)
@ConditionalOnClass({NatsClient.class, AsyncNatsConsumerPool.class})
@Order(Ordered.HIGHEST_PRECEDENCE)
public class NatsConfig {

    @Autowired
    private NatsProperties natsProperties;

    @Bean(name = "asyncNatsConsumerPool")
    @ConditionalOnMissingBean(AsyncNatsConsumerPool.class)
    public AsyncNatsConsumerPool asyncNatsConsumerPool() {
        return new AsyncNatsConsumerPool();
    }

    @Bean(name = "natsClient")
    @ConditionalOnMissingBean(NatsClient.class)
    public NatsClient natsClient() throws IOException, InterruptedException {
        String url = natsProperties.getUrl();
        if (StringUtils.isEmpty(url)) {
            throw new NullPointerException("nats url must not be null");
        }
        return new NatsClient(url);
    }
}
